#include "historymanager.h"
#include <QDir>
#include <QStandardPaths>
#include <QCoreApplication>
#include <QDebug>

HistoryManager::HistoryManager(QObject *parent) : QObject(parent),
    m_settings(new QSettings(QSettings::IniFormat, QSettings::UserScope,
                             QCoreApplication::organizationName(),
                             QCoreApplication::applicationName()))
{
    loadHistory();
}

HistoryManager::~HistoryManager()
{
    saveHistory();
    delete m_settings;
}

QStringList HistoryManager::recentFiles() const
{
    return m_recentFiles;
}

void HistoryManager::addRecentFile(const QString &path, int maxCount)
{
    if (path.isEmpty()) return;

    // 解析规范化路径
    QString normalizedPath = QFileInfo(path).canonicalFilePath();
    if (normalizedPath.isEmpty()) return;

    // 如果已存在则移到顶部
    removeRecentFile(normalizedPath);

    // 添加到列表开头
    m_recentFiles.prepend(normalizedPath);

    // 限制列表长度
    while (m_recentFiles.size() > maxCount) {
        m_recentFiles.removeLast();
    }

    // 保存并发出信号
    saveHistory();
    emit recentFilesChanged();
}

void HistoryManager::removeRecentFile(const QString &path)
{
    if (path.isEmpty()) return;

    QString normalizedPath = QFileInfo(path).canonicalFilePath();
    if (m_recentFiles.removeAll(normalizedPath) > 0) {
        saveHistory();
        emit recentFilesChanged();
    }
}

void HistoryManager::clearRecentFiles()
{
    if (!m_recentFiles.isEmpty()) {
        m_recentFiles.clear();
        saveHistory();
        emit recentFilesChanged();
    }
}

bool HistoryManager::contains(const QString &path) const
{
    if (path.isEmpty()) return false;
    return m_recentFiles.contains(QFileInfo(path).canonicalFilePath());
}

QString HistoryManager::displayName(const QString &path) const
{
    return QFileInfo(path).fileName();
}

QString HistoryManager::shortPath(const QString &path, int maxLength) const
{
    if (path.isEmpty()) return QString();

    QString normalizedPath = QDir::toNativeSeparators(path);
    if (normalizedPath.length() <= maxLength) {
        return normalizedPath;
    }

    // 尝试使用主目录缩写
    QString homePath = QDir::homePath();
    if (normalizedPath.startsWith(homePath)) {
        normalizedPath.replace(0, homePath.length(), "~");
        if (normalizedPath.length() <= maxLength) {
            return normalizedPath;
        }
    }

    // 截断中间部分
    QFileInfo fileInfo(path);
    QString fileName = fileInfo.fileName();
    QString dirPath = fileInfo.path();

    int remainingLength = maxLength - fileName.length() - 3; // 3 for "..."
    if (remainingLength <= 0) {
        // 如果文件名本身就太长，截断文件名
        return fileName.left(maxLength - 3) + "...";
    }

    // 从路径两端各取一部分
    int leftLength = remainingLength / 2;
    int rightLength = remainingLength - leftLength;

    return dirPath.left(leftLength) + "..." + dirPath.right(rightLength) + QDir::separator() + fileName;
}

void HistoryManager::loadHistory()
{
    m_recentFiles = m_settings->value("RecentFiles/List", QStringList()).toStringList();

    // 过滤掉不存在的文件，并规范化路径
    QStringList validFiles;
    for (const QString &path : m_recentFiles) {
        QFileInfo fileInfo(path);
        if (fileInfo.exists() && fileInfo.isFile()) {
            validFiles.append(fileInfo.canonicalFilePath());
        }
    }

    // 去重
    validFiles.removeDuplicates();

    if (m_recentFiles != validFiles) {
        m_recentFiles = validFiles;
        saveHistory(); // 保存过滤后的列表
    }
}

void HistoryManager::saveHistory()
{
    m_settings->setValue("RecentFiles/List", m_recentFiles);
    m_settings->sync();
}

bool HistoryManager::fileExists(const QString &path) const
{
    return QFileInfo::exists(path) && QFileInfo(path).isFile();
}